﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ModeloGaleriaNET;
using System.ComponentModel;
using CADs;
using AvalonDock;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ucObras.xaml
    /// </summary>
    public partial class ucObras : UserControl
    {
        private string[] permisos = new string[] { TiposRoles.CREAR_OBRA, TiposRoles.MODIFICAR_DATOS_OBRA,
            TiposRoles.ELIMINAR_OBRA, TiposRoles.VISUALIZAR_OBRA, TiposRoles.ASIGNAR_OBRAS_CLIENTES};
        private readonly int pageSize = int.Parse(CADs.Properties.Resources.PageSize);
        private readonly string title = "Gestión de obras";
        private bool loaded;
        private int numObras;
        private int pagenum;
        private bool success;
        private BackgroundWorker worker, workerPermisos;
        private List<Obra> obras;
        private ObraCAD obraCAD;
        private int? usuarioAlta;
        private Cliente cliente;
        private string usuario;
        private Dictionary<string, bool> permisosDatos;

        public ucObras()
        {
            InitializeComponent();
            usuarioAlta = null;
            cliente = null;
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            workerPermisos = new BackgroundWorker();
            workerPermisos.DoWork += workerPermisos_DoWork;
            workerPermisos.RunWorkerCompleted += workerPermisos_RunWorkerCompleted;
            #endregion
            loaded = false;
        }

        public ucObras(int uAlta)
        {
            InitializeComponent();
            usuarioAlta = uAlta;
            cliente = null;
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            workerPermisos = new BackgroundWorker();
            workerPermisos.DoWork += workerPermisos_DoWork;
            workerPermisos.RunWorkerCompleted += workerPermisos_RunWorkerCompleted;
            #endregion
            loaded = false;
        }

        public ucObras(Cliente c)
        {
            InitializeComponent();
            usuarioAlta = null;
            cliente = c;
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            #endregion
            loaded = false;
        }

        private void workerPermisos_DoWork(object sender, DoWorkEventArgs e)
        {
            bool? value;
            
            usuario = Convert.ToString(Utilities.FindUsuarioData(typeof(UserWindow), this, "Name"));
            permisosDatos = new Dictionary<string, bool>();
            foreach (string s in permisos)
            {
                value = ManejadorRoles.Instance.CanUse(s, usuario);
                if (value != null)
                    permisosDatos.Add(s, value.Value);
            }
        }

        private void workerPermisos_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool value, value2, value3;
            IntPtr b;
            BitmapSource bs;

            if (permisosDatos == null || permisosDatos.Count != permisos.Length)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("No se han podido obtener los permisos", "Error",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                dgObras.MouseDoubleClick -= dgObras_MouseDoubleClick;
                btAnterior.IsEnabled = btSiguiente.IsEnabled = btNuevo.IsEnabled =
                    btBuscar.IsEnabled = btLimpiar.IsEnabled = false;
                b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtNuevo.Source = bs;

                dgObras.ItemsSource = null;
                dgObras.Items.Clear();
            }
            else
            {
                permisosDatos.TryGetValue(TiposRoles.VISUALIZAR_OBRA, out value);
                if (value == false)
                {
                    dgObras.MouseDoubleClick -= dgObras_MouseDoubleClick;
                    btNuevo.IsEnabled = false;
                    b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                    bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                      System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    this.imgBtNuevo.Source = bs;
                }
                else
                {
                    permisosDatos.TryGetValue(TiposRoles.MODIFICAR_DATOS_OBRA, out value);
                    permisosDatos.TryGetValue(TiposRoles.ELIMINAR_OBRA, out value2);
                    permisosDatos.TryGetValue(TiposRoles.ASIGNAR_OBRAS_CLIENTES, out value3);
                    if (value2 == false && value == false && value3 == false)
                        dgObras.MouseDoubleClick -= dgObras_MouseDoubleClick;

                    permisosDatos.TryGetValue(TiposRoles.CREAR_OBRA, out value);
                    if (value == false)
                    {
                        b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                          System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        this.imgBtNuevo.Source = bs;
                        btNuevo.IsEnabled = false;
                    }
                    else
                    {
                        b = Properties.Resources.Agregar_24.GetHbitmap();
                        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                          System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        this.imgBtNuevo.Source = bs;
                        btNuevo.IsEnabled = true;
                    }
                }
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                obras = obraCAD.GetObrasPaginated(pagenum);
                numObras = obraCAD.GetObrasCount();
                success = true;
            }
            catch (Exception)
            {
                try
                {
                    System.Threading.Thread.Sleep(1500);
                    obras = obraCAD.GetObrasPaginated(pagenum);
                    numObras = obraCAD.GetObrasCount();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                }
            }
        }

        private void btAnterior_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum--;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum++;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtSiguiente != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Right_24.GetHbitmap() : Properties.Resources.RightBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtSiguiente.Source = bs;
            }
        }

        private void btAnterior_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtAnterior != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Left_24.GetHbitmap() : Properties.Resources.LeftBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtAnterior.Source = bs;
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _busyIndicator.IsBusy = false;
            if (success)
            {
                dgObras.ItemsSource = obras;
                tbPaginacion.Visibility = Visibility.Visible;
                UpdatePaginationControls();
            }
            else
            {
                dgObras.ItemsSource = null;
                Xceed.Wpf.Toolkit.MessageBox.Show("No se ha podido realizar la búsqueda",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public string Title
        {
            get { return title; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            List<ObraFilter> filtros;
            ObraFilter filtro;

            if (!loaded)
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    obraCAD = new ObraCAD();

                    if (usuarioAlta == null && cliente == null)
                        obraCAD.SetQueryFilters(null);
                    else if (usuarioAlta != null)
                    {
                        filtro = new ObraFilter("it.usuarioAlta = @inputAlta");
                        filtro.Parameters.Add(new ObjectParameter("inputAlta", usuarioAlta));
                        filtros = new List<ObraFilter>();
                        filtros.Add(filtro);
                        obraCAD.SetQueryFilters(filtros);
                    }
                    else if (cliente != null)
                    {
                        filtro = new ObraFilter(@"EXISTS (select cpo.obra from clientespropietariosobras as cpo where cpo.obra = it.id and cpo.cliente = @inputPropietario and cpo.fechaFin IS null)");
                        filtro.Parameters.Add(new ObjectParameter("inputPropietario", cliente.Id));
                        filtros = new List<ObraFilter>();
                        filtros.Add(filtro);
                        obraCAD.SetQueryFilters(filtros);
                    }

                    numObras = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();

                    if (workerPermisos.IsBusy == false)
                        workerPermisos.RunWorkerAsync();
                }
                loaded = true;
            }
        }

        private void UpdatePaginationControls()
        {
            String iniString = "0";
            String deString = "";

            if (numObras > 0)
                iniString = (pagenum * pageSize + 1).ToString();

            btAnterior.IsEnabled = pagenum == 0 ? false : true;

            if (pagenum + 1 >= numObras / (float)pageSize)
            {
                btSiguiente.IsEnabled = false;
                deString = numObras.ToString();
            }
            else
            {
                btSiguiente.IsEnabled = true;
                deString = ((pagenum + 1) * pageSize).ToString();
            }

            lbPagina.Content = iniString + " - " + deString + " de " + numObras;
        }

        private void btNuevo_Click(object sender, RoutedEventArgs e)
        {
            DocumentContent doc = FindDocumentContent(typeof(ucObraData));

            if (doc == null)
                ShowPageInParentDock<ucObraData>();
            else
                MessageBox.Show("Ya hay abierta una ventana de creación o edición de obras. Ciérrela antes de abrir otra.",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private DocumentContent FindDocumentContent(Type t)
        {
            AvalonDock.DockingManager manager;

            manager = ((AvalonDock.DocumentContent)this.Parent).Manager;
            // Buscamos si hay abierta una instancia del documento a abrir
            foreach (AvalonDock.DocumentContent doc in manager.Documents)
            {
                if (doc.Content.GetType() == t)
                    return doc;
            }
            return null;
        }

        public void ActualizarDataGrid()
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                dgObras.ItemsSource = null;
                numObras = -1;
                worker.RunWorkerAsync();
            }
        }

        private void OpenNewDocument(UserControl c)
        {
            DependencyObject padre;

            try
            {
                padre = this.Parent;
                if (padre is AvalonDock.DocumentContent)
                {
                    padre = ((AvalonDock.DocumentContent)padre).Manager;
                    if (padre is AvalonDock.DockingManager)
                    {
                        padre = ((AvalonDock.DockingManager)padre).Parent;
                        if (padre is Grid)
                        {
                            padre = ((Grid)padre).Parent;

                            if (padre is UserWindow)
                            {
                                if (c is ucObraData)
                                {
                                    ((UserWindow)padre).ShowPage<ucObraData>((ucObraData)c);
                                }
                            }
                            else
                                throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                        }
                        else
                            throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                    }
                    else
                        throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                }
                else
                    throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
            }
            catch (ErrorOpeningNewDocumentException ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void ShowPageInParentDock<T>(EntityObject obj = null) where T : UserControl
        {
            ucObraData control;

            control = obj != null ? new ucObraData((Obra)obj, usuario) : new ucObraData(usuario);
            control.ObraCAD = obraCAD;
            OpenNewDocument(control);
        }

        private void dgObras_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGrid grid;
            DataGridRow dgr;
            DocumentContent doc;
            
            if (sender != null)
            {
                grid = sender as DataGrid;
                if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                {
                    dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
                    if (dgr.Item is EntityObject)
                    {
                        doc = FindDocumentContent(typeof(ucObraData));
                        if (doc == null)
                            ShowPageInParentDock<ucObraData>(((EntityObject)dgr.Item));
                        else
                            MessageBox.Show("Ya hay abierta una ventana de creación o edición de obras. Ciérrela antes de abrir otra.",
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }    
        }

        private void btBuscar_Click(object sender, RoutedEventArgs e)
        {
            ObraFilterWindow busqueda;

            busqueda = new ObraFilterWindow();
            busqueda.ShowDialog();

            if (busqueda.Success) // Realizar búsqueda
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    obraCAD.SetQueryFilters(busqueda.Filters);
                    dgObras.ItemsSource = null;
                    dgObras.Items.Clear();
                    numObras = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
            }
        }

        private void btLimpiar_Click(object sender, RoutedEventArgs e)
        {
            _busyIndicator.IsBusy = true;
            obraCAD.SetQueryFilters(null);
            numObras = -1;
            pagenum = 0;
            worker.RunWorkerAsync();
        }
    }
}

